package com.sjtu.rental.controller;

import java.io.IOException;
import java.net.MalformedURLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.validator.GenericValidator;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alipay.AlipayBase;
import com.alipay.AlipayConfig;
import com.alipay.AlipayService;
import com.alipay.UtilDate;
import com.mysql.jdbc.StringUtils;
import com.sjtu.rental.common.Constant;
import com.sjtu.rental.common.PaginationSupport;
import com.sjtu.rental.entity.House;
import com.sjtu.rental.entity.UserInfo;
import com.sjtu.rental.exception.RegisterException;
import com.sjtu.rental.form.RegisterForm;
import com.sjtu.rental.form.SearchForm;
import com.sjtu.rental.services.HouseService;
import com.sjtu.rental.services.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private HouseService houseService;

	@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
	public String index(@PathVariable Long id, Model model) {
		// 已认证
		int confirmed = houseService.getCountByUserId(id,
				Constant.HOUSE_STATE_CONFIRMED);
		// 已缴费
		int hasPaid = houseService.getCountByUserId(id,
				Constant.HOUSE_STATE_PAID);
		// 已出租
		int hasRented = houseService.getCountByUserId(id,
				Constant.HOUSE_STATE_RENTED);
		// 预约
		int appointment = houseService.getAppointmentCountByUserId(id);
		// 所有
		int all = houseService.getCountByUserId(id, null);
		model.addAttribute("confirmed", confirmed);
		model.addAttribute("hasPaid", hasPaid);
		model.addAttribute("hasRented", hasRented);
		model.addAttribute("appointment", appointment);
		model.addAttribute("all", all);
		model.addAttribute("searchForm", new SearchForm());
		return "user/index";
	}

	@RequestMapping(value = "/user/profile", method = RequestMethod.GET)
	public String profile(Model model, HttpSession session) {
		RegisterForm form = new RegisterForm();
		UserInfo user = (UserInfo) session.getAttribute("user");
		form.setUser(user);
		model.addAttribute("form", form);
		model.addAttribute("searchForm", new SearchForm());
		return "user/profile";
	}

	@RequestMapping(value = "/user/profile", method = RequestMethod.POST)
	public String save(
			@Valid @ModelAttribute("form") RegisterForm registerForm,
			BindingResult br, Model model, HttpSession session, HttpServletRequest request) {
		UserInfo user = registerForm.getUser();
		if (GenericValidator.isBlankOrNull(user.getUiPassword())) {
			user.setUiPassword(((UserInfo) session.getAttribute("user"))
					.getUiPassword());
		}
		try {
			userService.saveOrUpdate(user);
			session.setAttribute("user", user);
		} catch (RegisterException e) {
			request.setAttribute("error", e.getMessage());
			return profile(model, session);
		}
		return "redirect:/user/" + user.getUiId();
	}

	@RequestMapping(value = "/user/house", method = RequestMethod.GET)
	public String houseList(
			@RequestParam(value = "page", required = false, defaultValue = "0") String page,
			@RequestParam(value = "state", required = false) Integer approveState,
			Model model, HttpSession session) {
		UserInfo user = (UserInfo) session.getAttribute("user");
		PaginationSupport p = houseService.getHousesByUserId(user.getUiId(),
				approveState, Integer.parseInt(page));
		p.setUrl("/user/house?state="
				+ (approveState == null ? "" : approveState) + "&page=");
		model.addAttribute("state", approveState);
		model.addAttribute("p", p);
		model.addAttribute("searchForm", new SearchForm());
		return "user/house";
	}
	
	@RequestMapping(value = "/user/houseall", method = RequestMethod.GET)
	public String houseAllList(
			@RequestParam(value = "page", required = false, defaultValue = "0") String page,
			@RequestParam(value = "state", required = false) Integer approveState,
			Model model, HttpSession session) {
		PaginationSupport p = houseService.getHousesByUserId(null,
				approveState, Integer.parseInt(page));
		p.setUrl("/user/houseall?state="
				+ (approveState == null ? "" : approveState) + "&page=");
		model.addAttribute("state", approveState);
		model.addAttribute("p", p);
		model.addAttribute("searchForm", new SearchForm());
		return "user/house";
	}

	@SuppressWarnings("static-access")
	@RequestMapping(value = "/user/pay/{hid}", method = RequestMethod.GET)
	public String pay(@PathVariable Integer hid, Model model,
			HttpSession session) {
		model.addAttribute("searchForm", new SearchForm());
		String input_charset = AlipayConfig.CharSet;
		String sign_type = AlipayConfig.sign_type;
		String seller_email = AlipayConfig.sellerEmail;
		String partner = AlipayConfig.partnerID;
		String key = AlipayConfig.key;

		String show_url = AlipayConfig.show_url;
		String notify_url = AlipayConfig.notify_url;
		String return_url = AlipayConfig.return_url;

		String antiphishing = AlipayConfig.antiphishing;

		// /////////////////////////////////////////////////////////////////////////////////

		// 以下参数是需要通过下单时的订单数据传入进来获得
		// 必填参数
		UtilDate date = new UtilDate();// 调取支付宝工具类生成订单号
		String out_trade_no = date.getOrderNum();// 请与贵网站订单系统中的唯一订单号匹配
		// 订单总金额，显示在支付宝收银台里的“应付总额”里

		House house = houseService.getById(new Long(hid));
		// String total_fee = house.getPrice() * 0.03 + "";
		String total_fee = "0.01";
		// 订单名称，显示在支付宝收银台里的“商品名称”里，显示在支付宝的交易管理的“商品名称”的列表里。
		String subject = "【" + house.getHousingName() + "】手续费";
		// 订单描述、订单详细、订单备注，显示在支付宝收银台里的“商品描述”里
		String body = "交大租房网会收取3%的佣金手续费，您发布的【" + house.getHousingName()
				+ "】租金为：" + house.getPrice() + "，3%的手续费为：" + house.getPrice()
				* 0.03 + "，但是系统演示需要，暂时只收你1分钱！";
		// 扩展功能参数——网银提前
		String paymethod = ""; // 默认支付方式，四个值可选：bankPay(网银); cartoon(卡通);
		// directPay(余额); CASH(网点支付)
		String defaultbank = ""; // 默认网银代号，代号列表见http://club.alipay.com/read.php?tid=8681379
		paymethod = "directPay";

		// 扩展功能参数——防钓鱼
		String encrypt_key = ""; // 防钓鱼时间戳，初始值
		String exter_invoke_ip = ""; // 客户端的IP地址，初始值
		if (antiphishing.equals("1")) {
			try {
				encrypt_key = AlipayBase.query_timestamp(partner);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			exter_invoke_ip = ""; // 获取客户端的IP地址，建议：编写获取客户端IP地址的程序
		}

		// 扩展功能参数——其他
		String extra_common_param = ""; // 自定义参数，可存放任何内容（除=、&等特殊字符外），不会显示在页面上
		String buyer_email = ""; // 默认买家支付宝账号

		// 扩展功能参数——分润(若要使用，请按照注释要求的格式赋值)
		String royalty_type = ""; // 提成类型，该值为固定值：10，不需要修改
		String royalty_parameters = "";
		// 提成信息集，与需要结合商户网站自身情况动态获取每笔交易的各分润收款账号、各分润金额、各分润说明。最多只能设置10条
		// 提成信息集格式为：收款方Email_1^金额1^备注1|收款方Email_2^金额2^备注2
		// 如：
		// royalty_type = "10"
		// royalty_parameters =
		// "111@126.com^0.01^分润备注一|222@126.com^0.01^分润备注二"

		// 扩展功能参数——自定义超时(若要使用，请按照注释要求的格式赋值)
		// 该功能默认不开通，需联系客户经理咨询
		// 超时时间，不填默认是15天。八个值可选：1h(1小时),2h(2小时),3h(3小时),1d(1天),3d(3天),7d(7天),15d(15天),1c(当天)
		String it_b_pay = "";
		// MsAccountPay pay = new MsAccountPay();
		// pay.setAccountId(((MsAccount) httpSession.getAttribute("account"))
		// .getId());
		// pay.setChargeId(mc.getId());
		// pay.setFinished((short) 0);
		// pay.setOrderId(out_trade_no);
		// pay.setOrderTime(new Date());
		// accountService.saveOrUpdate(pay);

		String strUrl = AlipayService.CreateUrl(partner, seller_email,
				return_url, notify_url, show_url, out_trade_no, subject, body,
				total_fee, paymethod, defaultbank, encrypt_key,
				exter_invoke_ip, extra_common_param, buyer_email, royalty_type,
				royalty_parameters, it_b_pay, input_charset, key, sign_type);
		return "redirect:" + strUrl;
	}

	@RequestMapping(value = "/user/payok/{hid}", method = RequestMethod.GET)
	public String payok(@PathVariable Integer hid, Model model,
			HttpSession session) {
		houseService.changeHouseState(new Long(hid), Constant.HOUSE_STATE_PAID);
		return "redirect:/user/houseall";
	}

	@RequestMapping(value = "/user/appointment", method = RequestMethod.GET)
	public String appointmentList(
			@RequestParam(value = "page", required = false, defaultValue = "0") String page,
			Model model, HttpSession session) {
		UserInfo user = (UserInfo) session.getAttribute("user");
		PaginationSupport p = houseService.getAppointmentHouses(user.getUiId(),
				Integer.parseInt(page));
		p.setUrl("/user/appointment&page=");
		model.addAttribute("p", p);
		model.addAttribute("searchForm", new SearchForm());
		return "user/appointment";
	}

	@RequestMapping(value = "/user/order", method = RequestMethod.GET)
	public String orderList(
			@RequestParam(value = "page", required = false, defaultValue = "0") String page,
			Model model, HttpSession session) {
		UserInfo user = (UserInfo) session.getAttribute("user");
		PaginationSupport p = houseService.getOrderHouses(user.getUiId(),
				Integer.parseInt(page));
		p.setUrl("/user/order&page=");
		model.addAttribute("p", p);
		model.addAttribute("searchForm", new SearchForm());
		return "user/orders";
	}

	@RequestMapping(value = "/user/marks", method = RequestMethod.POST)
	public String marks(HttpServletRequest request) {
		if (!StringUtils.isNullOrEmpty(request.getParameter("marks"))
				|| !StringUtils.isNullOrEmpty(request.getParameter("remark"))) {
			houseService.rating(
					Long.parseLong(request.getParameter("orderId")), request
							.getParameter("marks"), request
							.getParameter("remark"));
		}
		return "redirect:/user/order";
	}
}
